// src/components/VersionCompare.js
import React, { useState, useEffect } from 'react';
import {
  Table,
  Card,
  Tag,
  Space,
  Typography,
  Alert,
  Spin,
  Row,
  Col,
  Select,
  Button,
  Breadcrumb,
} from 'antd';
import { ArrowLeftOutlined, SwapOutlined } from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import axios from 'axios';
import moment from 'moment';

const { Title, Text } = Typography;
const { Option } = Select;

const VersionCompare = () => {
  const navigate = useNavigate();
  const [loading, setLoading] = useState(false);
  const [changes, setChanges] = useState([]);
  const [files, setFiles] = useState([]);
  const [selectedFile, setSelectedFile] = useState(null);
  const [versions, setVersions] = useState([]);
  const [version1, setVersion1] = useState(null);
  const [version2, setVersion2] = useState(null);
  const [versionInfo1, setVersionInfo1] = useState(null);
  const [versionInfo2, setVersionInfo2] = useState(null);

  useEffect(() => {
    fetchFiles();
  }, []);

  const fetchFiles = async () => {
    try {
      const response = await axios.get('/api/files');
      setFiles(response.data);
    } catch (error) {
      console.error('获取文件列表失败:', error);
    }
  };

  const fetchVersions = async (fileId) => {
    try {
      const response = await axios.get(`/api/files/${fileId}/versions`);
      setVersions(response.data);
      setVersion1(null);
      setVersion2(null);
      setChanges([]);
    } catch (error) {
      console.error('获取版本列表失败:', error);
    }
  };

  const fetchComparison = async () => {
    if (!version1 || !version2) return;
    
    setLoading(true);
    try {
      const response = await axios.get(`/api/versions/compare/${version1}/${version2}`);
      setChanges(response.data.changes);
      
      // 获取版本信息
      const [info1, info2] = await Promise.all([
        axios.get(`/api/versions/${version1}/data`),
        axios.get(`/api/versions/${version2}/data`)
      ]);
      
      setVersionInfo1(info1.data.versionInfo);
      setVersionInfo2(info2.data.versionInfo);
    } catch (error) {
      console.error('获取对比数据失败:', error);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    if (version1 && version2) {
      fetchComparison();
    }
  }, [version1, version2]);

  const getChangeTypeColor = (type) => {
    switch (type) {
      case 'added':
        return 'green';
      case 'deleted':
        return 'red';
      case 'modified':
        return 'orange';
      default:
        return 'default';
    }
  };

  const getChangeTypeText = (type) => {
    switch (type) {
      case 'added':
        return '新增';
      case 'deleted':
        return '删除';
      case 'modified':
        return '修改';
      default:
        return '未知';
    }
  };

  const columns = [
    {
      title: '行号',
      dataIndex: 'rowIndex',
      key: 'rowIndex',
      width: 80,
      render: (rowIndex) => rowIndex + 1,
    },
    {
      title: '列名',
      dataIndex: 'columnName',
      key: 'columnName',
      width: 150,
    },
    {
      title: '变更类型',
      dataIndex: 'changeType',
      key: 'changeType',
      width: 100,
      render: (type) => (
        <Tag color={getChangeTypeColor(type)}>
          {getChangeTypeText(type)}
        </Tag>
      ),
    },
    {
            title: '原值',
      dataIndex: 'oldValue',
      key: 'oldValue',
      width: 200,
      render: (value) => (
        <Text code style={{ backgroundColor: '#fff2f0' }}>
          {value || '(空)'}
        </Text>
      ),
    },
    {
      title: '新值',
      dataIndex: 'newValue',
      key: 'newValue',
      width: 200,
      render: (value) => (
        <Text code style={{ backgroundColor: '#f6ffed' }}>
          {value || '(空)'}
        </Text>
      ),
    },
  ];

  const getStatistics = () => {
    const stats = {
      total: changes.length,
      added: changes.filter(c => c.changeType === 'added').length,
      deleted: changes.filter(c => c.changeType === 'deleted').length,
      modified: changes.filter(c => c.changeType === 'modified').length,
    };
    return stats;
  };

  const stats = getStatistics();

  return (
    <div>
      <Row gutter={[16, 16]} style={{ marginBottom: 24 }}>
        <Col span={24}>
          <Card>
            {/* 面包屑导航 */}
            <Breadcrumb style={{ marginBottom: 16 }}>
              <Breadcrumb.Item>
                <Button 
                  type="link" 
                  icon={<ArrowLeftOutlined />}
                  onClick={() => navigate('/')}
                  style={{ padding: 0 }}
                >
                  文件列表
                </Button>
              </Breadcrumb.Item>
              <Breadcrumb.Item>版本对比</Breadcrumb.Item>
            </Breadcrumb>

            <Title level={3}>
              <SwapOutlined style={{ marginRight: 8 }} />
              版本对比
            </Title>
            
            {/* 版本选择器 */}
            <Row gutter={[16, 16]} style={{ marginBottom: 24 }}>
              <Col span={24}>
                <Card size="small" title="选择对比版本">
                  <Row gutter={[16, 16]}>
                    <Col span={8}>
                      <Space direction="vertical" style={{ width: '100%' }}>
                        <Text strong>选择文件:</Text>
                        <Select
                          style={{ width: '100%' }}
                          placeholder="请选择文件"
                          value={selectedFile}
                          onChange={(value) => {
                            setSelectedFile(value);
                            fetchVersions(value);
                          }}
                        >
                          {files.map(file => (
                            <Option key={file.id} value={file.id}>
                              {file.original_name} ({file.version_count} 个版本)
                            </Option>
                          ))}
                        </Select>
                      </Space>
                    </Col>
                    
                    <Col span={8}>
                      <Space direction="vertical" style={{ width: '100%' }}>
                        <Text strong>版本 1:</Text>
                        <Select
                          style={{ width: '100%' }}
                          placeholder="请选择版本 1"
                          value={version1}
                          onChange={setVersion1}
                          disabled={!selectedFile}
                        >
                          {versions.map(version => (
                            <Option key={version.id} value={version.id}>
                              v{version.version} - {version.submitter} ({moment(version.created_at).format('MM-DD HH:mm')})
                            </Option>
                          ))}
                        </Select>
                      </Space>
                    </Col>
                    
                    <Col span={8}>
                      <Space direction="vertical" style={{ width: '100%' }}>
                        <Text strong>版本 2:</Text>
                        <Select
                          style={{ width: '100%' }}
                          placeholder="请选择版本 2"
                          value={version2}
                          onChange={setVersion2}
                          disabled={!selectedFile}
                        >
                          {versions.map(version => (
                            <Option key={version.id} value={version.id}>
                              v{version.version} - {version.submitter} ({moment(version.created_at).format('MM-DD HH:mm')})
                            </Option>
                          ))}
                        </Select>
                      </Space>
                    </Col>
                  </Row>
                </Card>
              </Col>
            </Row>

            {/* 版本信息对比 */}
            {versionInfo1 && versionInfo2 && (
              <Row gutter={[16, 16]} style={{ marginBottom: 24 }}>
                <Col span={12}>
                  <Card size="small" title={`版本 ${versionInfo1.version}`}>
                    <Space direction="vertical">
                      <Text><strong>文件名:</strong> {versionInfo1.original_name}</Text>
                      <Text><strong>提交人:</strong> {versionInfo1.submitter}</Text>
                      <Text><strong>时间:</strong> {moment(versionInfo1.created_at).format('YYYY-MM-DD HH:mm:ss')}</Text>
                      <Text><strong>大小:</strong> {(versionInfo1.file_size / 1024).toFixed(2)} KB</Text>
                      <Text><strong>说明:</strong> {versionInfo1.change_description}</Text>
                    </Space>
                  </Card>
                </Col>
                
                <Col span={12}>
                  <Card size="small" title={`版本 ${versionInfo2.version}`}>
                    <Space direction="vertical">
                      <Text><strong>文件名:</strong> {versionInfo2.original_name}</Text>
                      <Text><strong>提交人:</strong> {versionInfo2.submitter}</Text>
                      <Text><strong>时间:</strong> {moment(versionInfo2.created_at).format('YYYY-MM-DD HH:mm:ss')}</Text>
                      <Text><strong>大小:</strong> {(versionInfo2.file_size / 1024).toFixed(2)} KB</Text>
                      <Text><strong>说明:</strong> {versionInfo2.change_description}</Text>
                    </Space>
                  </Card>
                </Col>
              </Row>
            )}

            {/* 统计信息 */}
            {version1 && version2 && (
              <Row gutter={[16, 16]} style={{ marginBottom: 24 }}>
                <Col span={6}>
                  <Card size="small">
                    <div style={{ textAlign: 'center' }}>
                      <div style={{ fontSize: 24, fontWeight: 'bold', color: '#1890ff' }}>
                        {stats.total}
                      </div>
                      <div>总变更</div>
                    </div>
                  </Card>
                </Col>
                
                <Col span={6}>
                  <Card size="small">
                    <div style={{ textAlign: 'center' }}>
                      <div style={{ fontSize: 24, fontWeight: 'bold', color: '#52c41a' }}>
                        {stats.added}
                      </div>
                      <div>新增</div>
                    </div>
                  </Card>
                </Col>
                
                <Col span={6}>
                  <Card size="small">
                    <div style={{ textAlign: 'center' }}>
                      <div style={{ fontSize: 24, fontWeight: 'bold', color: '#faad14' }}>
                        {stats.modified}
                      </div>
                      <div>修改</div>
                    </div>
                  </Card>
                </Col>
                
                <Col span={6}>
                  <Card size="small">
                    <div style={{ textAlign: 'center' }}>
                      <div style={{ fontSize: 24, fontWeight: 'bold', color: '#ff4d4f' }}>
                        {stats.deleted}
                      </div>
                      <div>删除</div>
                    </div>
                  </Card>
                </Col>
              </Row>
            )}

            {/* 对比结果 */}
            {version1 && version2 && (
              <>
                {changes.length === 0 && !loading ? (
                  <Alert
                    message="无变更"
                    description="两个版本之间没有发现任何差异"
                    type="info"
                    showIcon
                  />
                ) : (
                  <Spin spinning={loading}>
                    <Table
                      columns={columns}
                      dataSource={changes}
                      rowKey={(record, index) => `${record.rowIndex}-${record.columnName}-${index}`}
                      pagination={{
                        pageSize: 20,
                        showSizeChanger: true,
                        showQuickJumper: true,
                        showTotal: (total) => `共 ${total} 条变更`,
                      }}
                      scroll={{ y: 600 }}
                    />
                  </Spin>
                )}
              </>
            )}

            {!version1 || !version2 ? (
              <Alert
                message="请选择两个版本进行对比"
                description="请先选择文件，然后选择两个不同的版本进行对比分析"
                type="info"
                showIcon
              />
            ) : null}
          </Card>
        </Col>
      </Row>
    </div>
  );
};

export default VersionCompare;